package net.wanho.service.impl;

import lombok.RequiredArgsConstructor;
import net.wanho.contant.UserConstant;
import net.wanho.mapper.PermissionMapper;
import net.wanho.mapper.RoleMapper;
import net.wanho.po.Permission;
import net.wanho.po.Role;
import net.wanho.service.MenuService;
import net.wanho.util.CurrentUtil;
import net.wanho.vo.MenuVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Author：汤小洋
 * Date：2025-09-26 14:34
 * Description：<描述>
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class MenuServiceImpl implements MenuService {

    private final RoleMapper roleMapper;
    private final PermissionMapper permissionMapper;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<MenuVo> findMenu() {
        // 从redis中读取菜单
        List<MenuVo> menus = (List<MenuVo>) redisTemplate.opsForValue().get(UserConstant.MENU_PREFIX + CurrentUtil.getId());
        if (!CollectionUtils.isEmpty(menus)){
            return menus;
        }

        // 获取当前用户的权限
        Role role = roleMapper.selectByUserId(CurrentUtil.getId());
        String[] ids = role.getPsIds().split(",");
        List<Permission> permissions = permissionMapper.selectBatch(ids);

        // 获取一级菜单
        menus = permissions.stream()
                .filter(item -> item.getPsPid() == 0)
                .map(item -> {
                    MenuVo menuVo = wrapper(item);

                    // 获取二级菜单
                    List<MenuVo> children = permissions.stream()
                            .filter(subItem -> subItem.getPsPid().equals(item.getPsId()))
                            .map(this::wrapper)
                            .collect(Collectors.toList());
                    menuVo.setChildren(children);
                    return menuVo;
                })
                .collect(Collectors.toList());

        // 将用户菜单存储到redis中
        redisTemplate.opsForValue().set(UserConstant.MENU_PREFIX + CurrentUtil.getId(), menus, 12, TimeUnit.HOURS);

        return menus;
    }

    /**
     * 将Permission对象转换成MenuVo对象
     * @param item
     */
    private MenuVo wrapper(Permission item) {
        MenuVo menuVo = new MenuVo();
        menuVo.setId(item.getPsId());
        menuVo.setAuthName(item.getPsName());
        menuVo.setPath(item.getPsApiPath());
        menuVo.setIcon(item.getPsC());
        menuVo.setOrder(item.getPsApiOrder());
        return menuVo;
    }
}
